<template>
  <div class="p-4 h-full">
    <div class="w-full h-full px-4 pb-4 overflow-auto fill-in-enterprise-indicators-table">
      <div class="flex flex-col">
        <h2 class="table-title text-center px-4">
          {{title}}
          <el-button type="primary" style="float: right;" :loading="submitting" icon="el-icon-top" @click="saveOrUpdate">上报</el-button>
          <el-button type="primary" style="float: right;margin-right: 10px;" icon="el-icon-bottom" @click="exportData">导出</el-button>
        </h2>
        <table class="report-table dark-report-table" ref="table">
          <thead>
            <tr>
              <th colspan="3" width="300" class="is-stable-cell line-height-8">月份</th>
              <th v-for="item in columns" :key="item" class="is-stable-cell py-2">{{item}}</th>
              <th class="no-border-right is-stable-cell py-2">{{year}}年</th>
            </tr>
          </thead>
          <tbody>
            <tr>
              <th rowspan="6" class="is-stable-cell">能源指标</th>
              <th colspan="2" class="is-stable-cell">
                <div class="table--cell">
                  <div class="label">用电量</div>
                  <p class="small">（吨标准煤）</p>
                </div>
              </th>
              <td v-for="(item, index) in electric" :key="index" class="is-editable-cell">
                <div class="input-cell">
                  <el-popover :disabled="popoverDisabled(electric[index])" trigger="click" :content="electric[index]" placement="top" popper-class="cell-popper">
                    <input slot="reference" type="text" :value="electric[index]" @click="clickHandler" @input="inputHandler(electric, index, $event)">
                  </el-popover>
                </div>
              </td>
              <td class="readonly">
                <el-tooltip :content="electricTotal" placement="top">
                  <div class="span-cell">
                    {{electricTotal}}
                  </div>
                </el-tooltip>
              </td>
            </tr>
            <tr>
              <th colspan="2" class="is-stable-cell">
                <div class="table--cell">
                  <div class="label">用水量</div>
                  <p class="small">（吨）</p>
                </div>
              </th>
              <td v-for="(item, index) in water" :key="index" class="is-editable-cell">
                <div class="input-cell">
                  <el-popover :disabled="popoverDisabled(water[index])" trigger="click" :content="water[index]" placement="top" popper-class="cell-popper">
                    <input slot="reference" type="text" :value="water[index]" @click="clickHandler" @input="inputHandler(water, index, $event)">
                  </el-popover>
                </div>
              </td>
              <td class="readonly">
                <el-tooltip :content="waterTotal" placement="top">
                  <div class="span-cell">
                    {{waterTotal}}
                  </div>
                </el-tooltip>
              </td>
            </tr>
            <tr>
              <th colspan="2" class="is-stable-cell">
                <div class="table--cell">
                  <div class="label">用气量</div>
                  <p class="small">（吨标准煤）</p>
                </div>
              </th>
              <td v-for="(item, index) in gas" :key="index" class="is-editable-cell">
                <div class="input-cell">
                  <el-popover :disabled="popoverDisabled(gas[index])" trigger="click" :content="gas[index]" placement="top" popper-class="cell-popper">
                    <input slot="reference" type="text" :value="gas[index]" @click="clickHandler" @input="inputHandler(gas, index, $event)">
                  </el-popover>
                </div>
              </td>
              <td class="readonly">
                <el-tooltip :content="gasTotal" placement="top">
                  <div class="span-cell">
                    {{gasTotal}}
                  </div>
                </el-tooltip>
              </td>
            </tr>
            <tr>
              <th colspan="2"  class="is-stable-cell">
                <div class="table--cell">
                  <div class="label">能源回收利用量</div>
                  <p class="small">（吨标准煤）</p>
                </div>
              </th>
              <td v-for="(item, index) in recycle" :key="index" class="is-editable-cell">
                <div class="input-cell">
                  <el-popover :disabled="popoverDisabled(recycle[index])" trigger="click" :content="recycle[index]" placement="top" popper-class="cell-popper">
                    <input slot="reference" type="text" :value="recycle[index]" @click="clickHandler" @input="inputHandler(recycle, index, $event)">
                  </el-popover>
                </div>
              </td>
              <td class="readonly">
                <el-tooltip :content="recycleTotal" placement="top">
                  <div class="span-cell">
                    {{recycleTotal}}
                  </div>
                </el-tooltip>
              </td>
            </tr>
            <tr>
              <th colspan="2" class="is-stable-cell">
                <div class="table--cell">
                  <div class="label">能源转化产出量</div>
                  <p class="small">（吨标准煤）</p>
                </div>
              </th>
              <td v-for="(item, index) in output" :key="index" class="is-editable-cell">
                <div class="input-cell">
                  <el-popover :disabled="popoverDisabled(output[index])" trigger="click" :content="output[index]" placement="top" popper-class="cell-popper">
                    <input slot="reference" type="text" :value="output[index]" @click="clickHandler" @input="inputHandler(output, index, $event)">
                  </el-popover>
                </div>
              </td>
              <td class="readonly">
                <el-tooltip :content="outputTotal" placement="top">
                  <div class="span-cell">
                    {{outputTotal}}
                  </div>
                </el-tooltip>
              </td>
            </tr>
            <tr>
              <th colspan="2" class="is-stable-cell">
                <div class="table--cell">
                  <div class="label">
                    综合能源消费量
                    <el-tooltip placement="top" content="综合能源消费量=(用电量+用气量)-(回收利用量+转化产出量)">
                      <i class="el-icon-info"></i>
                    </el-tooltip>
                  </div>
                  <p class="small">（吨标准煤）</p>
                </div>
              </th>
              <td v-for="(item, index) in comprehensive" :key="index" class="readonly">
                <el-tooltip :disabled="popoverDisabled(comprehensive[index])" :content="comprehensive[index]" placement="top">
                  <div class="span-cell">
                    {{comprehensive[index]}}
                  </div>
                </el-tooltip>
              </td>
              <td class="readonly">
                <el-tooltip :disabled="popoverDisabled(comprehensiveTotal)" :content="comprehensiveTotal" placement="top">
                  <div class="span-cell">
                    {{comprehensiveTotal}}
                  </div>
                </el-tooltip>
              </td>
            </tr>
            <tr>
              <th rowspan="4" class="no-border-bottom is-stable-cell">能效指标</th>
              <th colspan="2" class="is-stable-cell">
                <div class="table--cell">
                  <div class="label">工业总产值</div>
                  <p class="small">（万元）</p>
                </div>
              </th>
              <td v-for="(item, index) in gdp" :key="index" class="is-editable-cell">
                <div class="input-cell">
                  <el-popover :disabled="popoverDisabled(gdp[index])" trigger="click" :content="gdp[index]" placement="top" popper-class="cell-popper">
                    <input slot="reference" type="text" :value="gdp[index]" @click="clickHandler" @input="inputHandler(gdp, index, $event)">
                  </el-popover>
                </div>
              </td>
              <td class="readonly">
                <el-tooltip :disabled="popoverDisabled(gdpTotal)" :content="gdpTotal" placement="top">
                  <div class="span-cell">
                    {{gdpTotal}}
                  </div>
                </el-tooltip>
              </td>
            </tr>
            <tr>
              <th colspan="2" class="is-stable-cell">
                <div class="table--cell">
                  <div class="label">
                    万元产值综合能耗
                    <el-tooltip placement="top" content="万元产值综合能耗=(综合能源消费量×1000)÷工业总产值">
                      <i class="el-icon-info"></i>
                    </el-tooltip>
                  </div>
                  <p class="small">（千克标准煤/万元）</p>
                </div>
              </th>
              <td v-for="(item, index) in gdpRatio" :key="index" class="readonly">
                <el-tooltip :disabled="popoverDisabled(gdpRatio[index])" :content="gdpRatio[index]" placement="top">
                  <div class="span-cell">
                    {{gdpRatio[index]}}
                  </div>
                </el-tooltip>
              </td>
              <td class="readonly">
                <el-tooltip :disabled="popoverDisabled(gdpRatioTotal)" :content="gdpRatioTotal" placement="top">
                  <div class="span-cell">
                    {{gdpRatioTotal}}
                  </div>
                </el-tooltip>
              </td>
            </tr>
            <tr>
              <th colspan="2" class="is-stable-cell">
                <div class="table--cell">
                  <div class="label">工业增加值</div>
                  <p class="small">（万元）</p>
                </div>
              </th>
              <td v-for="(item, index) in add" :key="index" class="is-editable-cell">
                <div class="input-cell">
                  <el-popover :disabled="popoverDisabled(add[index])" trigger="click" :content="add[index]" placement="top" popper-class="cell-popper">
                    <input slot="reference" type="text" :value="add[index]" @click="clickHandler" @input="inputHandler(add, index, $event)">
                  </el-popover>
                </div>
              </td>
              <td class="readonly">
                <el-tooltip :disabled="popoverDisabled(addTotal)" :content="addTotal" placement="top">
                  <div class="span-cell">
                    {{addTotal}}
                  </div>
                </el-tooltip>
              </td>
            </tr>
            <tr>
              <th colspan="2" class="is-stable-cell">
                <div class="table--cell">
                  <div class="label">
                    万元增加值综合能耗
                    <el-tooltip placement="top" content="万元增加值综合能耗=(综合能源消费量×1000)÷工业增加值">
                      <i class="el-icon-info"></i>
                    </el-tooltip>
                  </div>
                  <p class="small">（千克标准煤/万元）</p>
                </div>
              </th>
              <td v-for="(item, index) in addRatio" :key="index" class="readonly">
                <el-tooltip :disabled="popoverDisabled(addRatio[index])" :content="addRatio[index]" placement="top">
                  <div class="span-cell">
                    {{addRatio[index]}}
                  </div>
                </el-tooltip>
              </td>
              <td class="readonly">
                <el-tooltip :disabled="popoverDisabled(addRatioTotal)" :content="addRatioTotal" placement="top">
                  <div class="span-cell">
                    {{addRatioTotal}}
                  </div>
                </el-tooltip>
              </td>
            </tr>
          </tbody>
        </table>
      </div>
    </div>
  </div>
</template>

<script>
import { stringToPositiveNumber } from '@/utils'
import { loadEnterpriseReporting, saveOrUpdate } from '@/api/enterpriseReporting'
import { simpleTable2Sheet } from '@/utils/sheet'

export default {
  name: 'fill-in-enterprise-indicators',
  data () {
    return {
      submitting: false,

      year: new Date().getFullYear(),
      columns: Array(12).fill(undefined).map((v, i) => (i + 1) + '月'),
      water: Array(12).fill(''),
      electric: Array(12).fill(''),
      gas: Array(12).fill(''),
      recycle: Array(12).fill(''),
      output: Array(12).fill(''),
      gdp: Array(12).fill(''),
      add: Array(12).fill(''),

      inputIndex: -1,
    }
  },
  computed: {
    title () {
      return `${this.year}年企业能源指标填报表`
    },
    comprehensive () {
      const { electric, gas, recycle, output } = this
      return Array(electric.length).fill(1).map((v, i) => {
        const result = (((Number(electric[i]) || 0) + (Number(gas[i]) || 0)) - ((Number(recycle[i]) || 0) + (Number(output[i]) || 0)))
        return result ? result.toFixed(2) : '-'
      })
    },
    gdpRatio () {
      const { comprehensive, gdp } = this
      return Array(comprehensive.length).fill(1).map((v, i) => {
        return Number(gdp[i]) ? ((Number(comprehensive[i]) || 0) * 1000 / Number(gdp[i])).toFixed(2) : '-'
      })
    },
    addRatio () {
      const { comprehensive, add } = this
      return Array(comprehensive.length).fill(1).map((v, i) => {
        return Number(add[i]) ? ((Number(comprehensive[i]) || 0) * 1000 / Number(add[i])).toFixed(2) : '-'
      })
    },
    electricTotal () {
      return this.electric.reduce((acc, v) => {
        acc = (Number(acc) || 0) + (Number(v) || 0)
        return acc
      }).toFixed(2)
    },
    waterTotal () {
      return this.water.reduce((acc, v) => {
        acc = (Number(acc) || 0) + (Number(v) || 0)
        return acc
      }).toFixed(2)
    },
    gasTotal () {
      return this.gas.reduce((acc, v) => {
        acc = (Number(acc) || 0) + (Number(v) || 0)
        return acc
      }).toFixed(2)
    },
    recycleTotal () {
      return this.recycle.reduce((acc, v) => {
        acc = (Number(acc) || 0) + (Number(v) || 0)
        return acc
      }).toFixed(2)
    },
    outputTotal () {
      return this.output.reduce((acc, v) => {
        acc = (Number(acc) || 0) + (Number(v) || 0)
        return acc
      }).toFixed(2)
    },
    comprehensiveTotal () {
      // const { electricTotal, gasTotal, recycleTotal, outputTotal } = this
      // return ((Number(electricTotal) || 0) + (Number(gasTotal) || 0) - (Number(recycleTotal) || 0) - (Number(outputTotal) || 0)).toFixed(2)
      return this.comprehensive.reduce((acc, v) => {
        acc = (Number(acc) || 0) + (Number(v) || 0)
        return acc
      }).toFixed(2)
    },
    gdpTotal () {
      return this.gdp.reduce((acc, v) => {
        acc = (Number(acc) || 0) + (Number(v) || 0)
        return acc
      }).toFixed(2)
    },
    gdpRatioTotal () {
      const { gdpTotal, comprehensiveTotal } = this
      return Number(gdpTotal) ? ((Number(comprehensiveTotal) || 0) * 1000 / Number(gdpTotal)).toFixed(2) : '-'
    },
    addTotal () {
      return this.add.reduce((acc, v) => {
        acc = (Number(acc) || 0) + (Number(v) || 0)
        return acc
      }).toFixed(2)
    },
    addRatioTotal () {
      const { addTotal, comprehensiveTotal } = this
      return Number(addTotal) ? ((Number(comprehensiveTotal) || 0) * 1000 / Number(addTotal)).toFixed(2) : '-'
    },
  },
  beforeDestroy () {
    this.unbindArrowKeyEvent()
  },
  mounted () {
    this.loadEnterpriseReporting()
    this.initInputIndex()
    this.bindArrowKeyEvent()
  },
  methods: {
    popoverDisabled (val) {
      return val === '-' || val == null || val === '';
    },
    initInputIndex () {
      const inputs = document.querySelectorAll('.input-cell input')
      inputs.forEach((input, index) => {
        input.dataset.inputIndex = index
      })
    },
    eventHandler (e) {
      const { key, keyCode } = e
      if (keyCode < 37 || keyCode > 40 || key.indexOf('Arrow') === -1) {
        return false
      }
      const inputs = document.querySelectorAll('.input-cell input')
      let inputIndex = this.inputIndex
      const length = this.columns.length
      // ArrowUp
      if (key === 'ArrowUp' || keyCode === 38) {
        inputIndex -= length
      }
      // ArrowDown
      if (key === 'ArrowDown' || keyCode === 40) {
        inputIndex += length
      }
      // ArrowLeft
      if (key === 'ArrowLeft' || keyCode === 37) {
        inputIndex--
      }
      // ArrowRight
      if (key === 'ArrowRight' || keyCode === 39) {
        inputIndex++
      }
      if (inputIndex >= 0 && inputIndex <= inputs.length - 1) {
        this.inputIndex = inputIndex
      }
      inputs[this.inputIndex] && inputs[this.inputIndex].click()
    },
    bindArrowKeyEvent () {
      document.addEventListener('keyup', this.eventHandler, false)
    },
    unbindArrowKeyEvent () {
      document.removeEventListener('keyup', this.eventHandler, false)
    },
    inputHandler (type, index, evt) {
      const value = stringToPositiveNumber(evt.target.value)
      evt.target.value = value
      type.splice(index, 1, value)
    },
    clickHandler (evt) {
      // evt.target.select()
      this.inputIndex = Number(evt.target.dataset.inputIndex)
    },
    loadEnterpriseReporting () {
      return loadEnterpriseReporting().then(res => {
        if (res.code === 200) {
          res.data = res.data || []
          if (res.data.length === 0) {
            return
          }
          if (res.data.length === 13) {
            res.data = res.data.slice(0, 12)
          }
          function handler (key) {
            return function iterator (v) {
              return v[key] == null ? '' : v[key]
            }
          }
          this.water = res.data.map(handler('waterConsumption'))
          this.electric = res.data.map(handler('energyUsed'))
          this.gas = res.data.map(handler('gasConsumption'))
          this.recycle = res.data.map(handler('amountRecycled'))
          this.output = res.data.map(handler('conversionOutput'))
          this.gdp = res.data.map(handler('industrialOutput'))
          this.add = res.data.map(handler('industrialAddedValue'))
        }
      })
    },
    saveOrUpdate () {
      const { water, electric, gas, recycle, output, comprehensive, gdp, gdpRatio, add, addRatio } = this
      const params = Array(water.length).fill(1).map((v, i) => ({
        month: i + 1,
        waterConsumption: water[i],
        energyUsed: electric[i],
        gasConsumption: gas[i],
        amountRecycled: recycle[i],
        conversionOutput: output[i],
        comprehensiveEnergyConsumption: comprehensive[i],
        industrialOutput: gdp[i],
        tenThousandOutputValue: gdpRatio[i],
        industrialAddedValue: add[i],
        tenThousandValueAdded: addRatio[i],
      }))
      this.submitting = true
      return saveOrUpdate(params).then(res => {
        if (res.code === 200) {
          this.$message.success('提交成功')
        }
      }).finally(() => {
        this.submitting = false
      })
    },
    exportData () {
      const table = this.$refs.table
      const fileName = this.title + '.xlsx'
      simpleTable2Sheet(table, fileName, this.title)
    },
  },
}
</script>

<style scoped>
.table--cell {
  line-height: 1.8;
}
.table--cell > p {
  margin: 0;
}
</style>
